<script setup>
import { Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { togPassword } from '@/api/user.js'
import { userStore } from '../../../stores/user'
import { useRouter } from 'vue-router'
defineOptions({
  name: 'AppTog'
})
const router = useRouter()
const form = ref(null)
const user = userStore()
const info = ref({
  loginname: user.userInfo.token,
  password: '',
  newPassword: ''
})
const rules = ref({
  password: [{ required: true, trigger: 'blur', message: '请输入旧密码' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      min: 8,
      max: 16,
      message: '密码长度在8到16个字符',
      trigger: 'blur'
    },
    {
      validator(rule, value, callback) {
        if (value === info.value.password)
          callback(new Error('新密码不能和旧密码相同'))
        callback()
      }
    }
  ]
})
const submit = async () => {
  await form.value.validate()
  const res = await togPassword(info.value)
  if (res.data.code != 200) ElMessage.error(res.data.msg)
  else {
    ElMessage.success('密码修改成功，请重新登录')
    user.removeUserInfo()
    router.push('/')
  }
}
</script>

<template>
  <el-form ref="form" :rules="rules" class="my-5" :model="info">
    <el-text class="d-block text-end my-4"
      >账户{{ user.userInfo.token }}</el-text
    >

    <el-form-item class="my-5" label="旧密码：" prop="password">
      <el-input type="password" v-model="info.password">
        <template #prepend>
          <el-icon>
            <Lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="my-5" label="新密码：" prop="newPassword">
      <el-input type="password" v-model="info.newPassword">
        <template #prepend>
          <el-icon>
            <Lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <div class="w-100 d-flex justify-content-center">
        <el-button class="mx-3" type="info" plain> 取消 </el-button>
        <el-button class="mx-3" type="primary" @click="submit" plain>
          修改
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped></style>
